package com.eportal.controller.background;

import com.alibaba.fastjson.JSONObject;
import com.eportal.action.background.AuthAction;
import com.eportal.base.BaseDAO;
import com.eportal.domain.Sysmenu;
import com.eportal.domain.Sysopt;
import com.eportal.service.SysmenuService;
import com.eportal.util.CommonUtil;
import com.eportal.util.HomePageConfig;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 权限管理相关（菜单?）
 * Created by Saber on 2017/8/18.
 */
@Controller
@RequestMapping(value = "/admin/auth")
public class AuthController {

    private static Logger logger = LoggerFactory.getLogger(AuthController.class.getName());

    @Resource
    private SysmenuService sysmenuService;

    @Resource(name="dao")
    private BaseDAO dao;

    /**
     * 二级菜单
     * @author Saber
     * @Date 2017/8/18 上午9:27
     * @param request
     * @param mpid          父菜单id
     * @see AuthAction#menus()
     * @return
     */
    @RequestMapping(value = "menus.json")
    @ResponseBody
    public JSONObject menus(HttpServletRequest request,String mpid){

        JSONObject json = new JSONObject();

        try {
            String homePageConfig = HomePageConfig.WUYEJIAOFEI;
            String propertyPaySid = homePageConfig.split(",")[0];//物业缴费sid
            String homePageConfig2 = HomePageConfig.SHUIFEI;
            String waterPaySid = homePageConfig2.split(",")[0];//水费缴费sid
            String homePageConfig3 = HomePageConfig.TINGCHEFEI;
            String stopPaySid = homePageConfig3.split(",")[0];//停车缴费sid
            List<Sysmenu> sysmenus = null;
            Map<String, Object> map = (Map<String, Object>) request.getSession().getAttribute("auths");
            if(StringUtils.isNotBlank(mpid)){
                if(propertyPaySid.equals(mpid)){//缴费管理
                    sysmenus = getProperMenus(propertyPaySid,"1");
                }else if(waterPaySid.equals(mpid)){//水费缴费管理
                    sysmenus = getProperMenus(waterPaySid,"2");
                }else if(stopPaySid.equals(mpid)){//停车费缴费管理
                    sysmenus = getProperMenus(stopPaySid,"3");
                }else{
                    sysmenus = (List<Sysmenu>) map.get("menus");
                    for (Sysmenu menu : sysmenus) {
                        String url = menu.getmUrl();
                        if (url != null && url.trim().length() > 0) {
                            String[] temp = url.split(",");
                            menu.setmUrl(temp[0]);
                        }
                    }
                }
            }else{
                sysmenus = (List<Sysmenu>) map.get("menus");
                for (Sysmenu menu : sysmenus) {
                    String url = menu.getmUrl();
                    if (url != null && url.trim().length() > 0) {
                        String[] temp = url.split(",");
                        menu.setmUrl(temp[0]);
                    }
                }
            }

            json.put("code",1);
            json.put("msg","ok");
            json.put("data",sysmenus);
            return json;
        }catch (Exception e){
            e.printStackTrace();
            logger.error("二级菜单异常:", e);
            json.put("code", 0);
            json.put("msg", "服务器发生异常:" + e.getMessage());
            json.put("data", null);
            return json;
        }
    }

    /**
     * @author Saber
     * @Date 2017/8/18 上午9:32
     * @param sid
     * @param type
     * @see AuthAction#getProperMenus(String, String)
     * @return
     */
    public List<Sysmenu> getProperMenus(String sid, String type){
        //物业缴费等菜单集合
        List<Sysmenu> propertyPayMenus = new ArrayList<Sysmenu>();
        int userRole =  (Integer) CommonUtil.getHttpRequest().getSession().getAttribute("userRole");
        Sysopt user = (Sysopt) CommonUtil.getHttpRequest().getSession().getAttribute("user");

        StringBuffer sbsql = new StringBuffer();
        sbsql.append("select s.sid,s.mname,s.murl,s.mpno,s.mlevel,s.msort,s.misleaf,s.status,s.mtype,s.type as ttype,s.mcname,s.picname from sysmenu s where s.sid=");
        sbsql.append(sid);
        if(userRole ==5 || userRole ==6){
            sbsql.append(" union all ");
            sbsql.append("select * from (select m.sid as sid,m.item_name as mname,'/admin/propertyPay_listPropertyPayView.action?type=");
            sbsql.append(type);
            sbsql.append("'|| '&' ||'sid='||m.sid as murl,'");
            sbsql.append(sid);
            sbsql.append("' as mpno,1 as mlevel,'1'as msort,'1'as misleaf,'1'as status,'2'as mtype,0 as ttype,m.item_name as mcname,'' as picname  from fee_main m where m.type=");
            sbsql.append(type);
            sbsql.append(" and m.communityid=");
            sbsql.append(user.getCommunityId());
            sbsql.append(" order by m.sid desc)");
        }

        List<Map<String, Object>> listSysmenuMap = dao.queryBySql(sbsql.toString());

        if (listSysmenuMap != null && listSysmenuMap.size()>0) {
            propertyPayMenus = sysmenuService.getSysmenu(listSysmenuMap);
        }
        return propertyPayMenus;
    }
}
